package com.lxd.kyvideo.controller.frontend;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.core.annotation.Path;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponseBody;
import com.lxd.kyvideo.common.ApiResult;
import com.lxd.kyvideo.service.SmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@RestController
@RequestMapping("/api/sms")
@Api(tags = "短信服务")
public class SmsController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private StringRedisTemplate redisTemplate;



    @GetMapping("/send/{phoneNumber}")
    @ApiOperation("发送短信验证码")
    public ApiResult sendCode(@PathVariable String phoneNumber) {
        int randomCode = RandomUtil.randomInt(1000,9999);
        String redisCode = redisTemplate.opsForValue().get(phoneNumber);
        if(redisCode == null) {
            ApiResult jsonResult = smsService.sendSms(phoneNumber, randomCode);
            if(jsonResult.getCode() == 200) {
                SendSmsResponseBody responseBody = (SendSmsResponseBody) jsonResult.getData();
                if (responseBody.getCode().equals("OK")) {
                    redisTemplate.opsForValue().set(phoneNumber, String.valueOf(randomCode), 5, TimeUnit.MINUTES);
                    return jsonResult;
                } else {
                    return ApiResult.fail("短信发送失败!");
                }
            }
            else{
                return jsonResult;
            }
        }
        else {
            return ApiResult.fail("短信发送过于频繁,请稍后再发!");
        }
    }


    @PostMapping("/checkPhoneLogin/{phoneNumber}/{inputCode}")
    @ApiOperation("手机快捷登录")
    public ApiResult checkPhoneLogin(@PathVariable String phoneNumber, @PathVariable(required = false) String inputCode){
        Pattern p = Pattern.compile("^1[1345789]\\d{9}$");
        Matcher m = p.matcher(phoneNumber);
        if(StrUtil.isBlank(phoneNumber)){
            return ApiResult.fail("请输入手机号码");
        }
        else if(! m.matches()){
            return ApiResult.fail("请输入正确的手机号码");

        }
        if(StrUtil.isBlank(inputCode)) {
            return ApiResult.fail("请输入6位数字验证码");
        }
        String redisCode = redisTemplate.opsForValue().get(phoneNumber);
        if(redisCode != null) {
            if(! redisCode.equals(inputCode)){
                return ApiResult.fail("短信验证码错误，请重新获取！");
            }
            else {
                return ApiResult.ok("发送短信验证码成功，请注意查收！");
            }
        }
        else {
            return ApiResult.fail("短信验证码已失效，请重新获取！");
        }
    }
}
